package com.nymph.executor.resultset;

import com.nymph.mapping.MappedStatement;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: This is a sample class.
 * @Author: Simon
 */
public class DefaultResultSetHandler implements ResultSetHandler{

    private final MappedStatement mappedStatement;

    public DefaultResultSetHandler(MappedStatement ms){
        this.mappedStatement=ms;
    }

    @Override
    public <E> List<E> handleResultSets(ResultSet resultSet) {
        try{
            List<E> result=new ArrayList<>();
            if (resultSet==null){
                return null;
            }
            while (resultSet.next()){
                Class<?> entityClass = Class.forName(mappedStatement.getResultType());
                @SuppressWarnings("unchecked")
                E entity = (E)entityClass.newInstance();
                Field[] declaredFields = entityClass.getDeclaredFields();
                /**
                 * <select id="selectEmployee" resultType="com.example.Employee">
                 *     SELECT * FROM employees WHERE id = #{id}
                 * </select>
                 * 这里的resultType就是Employee
                 * 这里的entity就是new Employee()的意思 懂的dd
                 */
                for (Field field : declaredFields) {
                    field.setAccessible(true);
                    Class<?> fieldType = field.getType();

                    if (fieldType.equals(String.class)){
                        field.set(entity,resultSet.getString(field.getName()));
                    }
                    else if(fieldType.equals(int.class)||fieldType.equals(Integer.class))
                    {
                        field.set(entity,resultSet.getInt(field.getName()));
                    }
                    else
                    {
                        // 其他类型自己转换，这里就直接设置了
                        field.set(entity, resultSet.getObject(field.getName()));
                    }
                }
                result.add(entity);
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
}
